package com.example.demo4

import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.demo4.model.CardMatchingGame

class CardGameActivity : AppCompatActivity() {
    
    private lateinit var recyclerView: RecyclerView
    private lateinit var tvScore: TextView
    private lateinit var btnRestart: Button
    private lateinit var btnExit: Button
    
    private lateinit var game: CardMatchingGame
    private lateinit var adapter: CardAdapter
    private var cardCount = 24 // 默认竖屏24张
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)
        
        // 根据屏幕方向确定牌数
        val orientation = resources.configuration.orientation
        cardCount = if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            16 // 横屏16张
        } else {
            24 // 竖屏24张
        }
        
        initViews()
        initGame()
        setupListeners()
    }
    
    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        
        // 屏幕方向改变时重新初始化游戏
        val newCardCount = if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            16 // 横屏16张
        } else {
            24 // 竖屏24张
        }
        
        if (newCardCount != cardCount) {
            cardCount = newCardCount
            initGame()
        }
    }
    
    private fun initViews() {
        recyclerView = findViewById(R.id.recyclerViewCards)
        tvScore = findViewById(R.id.tvScore)
        btnRestart = findViewById(R.id.btnRestart)
        btnExit = findViewById(R.id.btnExit)
    }
    
    private fun initGame() {
        game = CardMatchingGame(cardCount)
        
        // 创建卡片列表
        val cards = mutableListOf<com.example.demo4.model.Card>()
        for (i in 0 until cardCount) {
            cards.add(game.cardAtIndex(i))
        }
        
        // 设置RecyclerView的布局管理器
        val spanCount = if (cardCount == 24) 4 else 4 // 竖屏24张用4列（6行），横屏16张也用4列（4行）
        val layoutManager = GridLayoutManager(this, spanCount)
        layoutManager.orientation = GridLayoutManager.VERTICAL
        recyclerView.layoutManager = layoutManager
        
        // 移除之前的ItemDecoration（如果有）
        for (i in recyclerView.itemDecorationCount - 1 downTo 0) {
            recyclerView.removeItemDecorationAt(i)
        }
        
        // 创建适配器
        adapter = CardAdapter(cards) { index ->
            onCardClicked(index)
        }
        
        recyclerView.adapter = adapter
        
        updateScore()
    }
    
    private fun onCardClicked(index: Int) {
        if (index >= cardCount) {
            return
        }
        
        val card = game.cardAtIndex(index)
        
        // 如果卡牌已经配对成功，不响应点击
        if (card.isMatched) {
            return
        }
        
        game.chooseCardAtIndex(index)
        updateUI()
    }
    
    private fun updateUI() {
        // 更新所有卡片
        val cards = mutableListOf<com.example.demo4.model.Card>()
        for (i in 0 until cardCount) {
            cards.add(game.cardAtIndex(i))
        }
        adapter.updateCards(cards)
        updateScore()
    }
    
    private fun updateScore() {
        tvScore.text = game.score.toString()
    }
    
    private fun setupListeners() {
        btnRestart.setOnClickListener {
            game.reset()
            updateUI()
        }
        
        btnExit.setOnClickListener {
            val resultIntent = Intent().apply {
                putExtra("score", game.score)
            }
            setResult(RESULT_OK, resultIntent)
            finish()
        }
    }
    
    override fun onBackPressed() {
        val resultIntent = Intent().apply {
            putExtra("score", game.score)
        }
        setResult(RESULT_OK, resultIntent)
        super.onBackPressed()
    }
}

